//
//  BQSelector.m
//  BQNavigator
//
//  Created by Zhiqiang Bao on 15-4-3.
//  Copyright (c) 2015年 Zhiqiang Bao. All rights reserved.
//

#import "BQSelector.h"
#import "BQRouter.h"

@interface BQSelector ()

@property (nonatomic, strong) BQRouter *router;
@property (nonatomic, strong) BQSelectorRunner *runner;

@end

@implementation BQSelector

#pragma mark - init

+ (BQSelector *)sharedInstance
{
    static dispatch_once_t onceTocken;
    static BQSelector *sharedInstance = nil;
    
    dispatch_once(&onceTocken, ^{
        if (sharedInstance == nil) {
            sharedInstance = [[BQSelector alloc] init];
        }
    });
    
    return sharedInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.router = [[BQRouter alloc] init];
        self.runner = [[BQSelectorRunner alloc] init];
    }
    return self;
}

#pragma mark - Register API

- (void)registerTarget:(id<BQSelectable>)target selector:(SEL)sel toEvent:(NSString *)event
{
    [self registerTarget:target selectorName:NSStringFromSelector(sel) toEvent:event];
}

- (void)registerTarget:(id<BQSelectable>)target selectorName:(NSString *)selName toEvent:(NSString *)event
{
    if (target == nil || selName.length == 0 || event.length == 0) return;
    
    BQSelectorOrder *order = [BQSelectorOrder orderWithEvent:event target:target selectorName:selName];
    
    [_router registerOrder:order toRunner:_runner];
}

#pragma mark  - Map API

- (void)mapEvent:(NSString *)first toEvent:(NSString *)second
{
    if (first.length == 0 || second.length == 0) return;
    
    BQSelectorOrder *order = (BQSelectorOrder *)[_router registeredOrderByEvent:second];
    
    BQSelectorOrder *otherOrder = [BQSelectorOrder orderWithEvent:first target:order.target selectorName:order.selectorName];
    
    [_router mapOrder:otherOrder toOrder:order];
}

#pragma mark - Open API

- (id)openEvent:(NSString *)event param:(id)param
{
    return [_router executeOrderEvent:event withOption:param];
}

@end
